#include "Socket.h"

Socket::Socket(int fd)
    : sockfd_(fd)
{
}

int Socket::fd(){
    return sockfd_;
}

void Socket::close()
{
    sockets::close(sockfd_);
}

void Socket::listen()
{
    sockets::listen(sockfd_);
}

int Socket::accept(sockaddr_in *peerAddr)
{
    sockaddr_in addr;
    int connfd = sockets::accept(sockfd_, &addr);
    if (connfd > 0)
    {
        *peerAddr = addr;
    }
    return connfd;
}

void Socket::shutdownWrite()
{
    sockets::shutdownWrite(sockfd_);
}

void Socket::setReusePort(bool on)
{
    int opt = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
}

void Socket::setReuseAddr(bool on)
{
    int opt = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
}

void Socket::setKeepAlive(bool on)
{
    int opt = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE, &opt, sizeof(opt));
}

void Socket::setTcpNoDelay(bool on)
{
    int opt = on ? 1 : 0;
    ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(opt));
}

void Socket::bindAddr(const sockaddr_in &addr)
{
    sockets::bind(sockfd_, addr);
}

Socket::~Socket()
{
    sockets::close(sockfd_);
}
